/*
 *  AMesh.cpp
 *  Amano Engine
 *
 *  Created by Aurelien Serandour on 07/03/11.
 *  Copyright 2011 __MyCompanyName__. All rights reserved.
 *
 */

#include "../include/AMesh.h"
#include <stddef.h>

using namespace Amano;

AMesh::AMesh()
{
	m_vertexBuffer = new float[3];
	m_normalBuffer = new float[3];
	m_indexBuffer = new GLuint[3];
}

AMesh::~AMesh()
{
	delete[] m_vertexBuffer;
	delete[] m_normalBuffer;
	delete[] m_indexBuffer;
}

void AMesh::createVBOs()
{
	glGenBuffers(1, &m_VBO);
	glBindBuffer(GL_ARRAY_BUFFER, m_VBO);
	glBufferData(GL_ARRAY_BUFFER, 2*3*m_numberOfVertices*sizeof(float), NULL, GL_STATIC_DRAW);
	glBufferSubData(GL_ARRAY_BUFFER, 0, 3*m_numberOfVertices*sizeof(float), m_vertexBuffer);
	glBufferSubData(GL_ARRAY_BUFFER, 3*m_numberOfVertices*sizeof(float), 3*m_numberOfVertices*sizeof(float), m_normalBuffer);
	glBindBuffer(GL_ARRAY_BUFFER, 0);
	
	glGenBuffers(1, &m_IBO);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_IBO);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, m_numberOfIndices*sizeof(int), NULL, GL_STATIC_DRAW);
    glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, m_numberOfIndices*sizeof(GLuint), m_indexBuffer);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}

void AMesh::deleteVBOs()
{
	glDeleteBuffers(1, &m_VBO);
	glDeleteBuffers(1, &m_IBO);
}

void AMesh::render()
{
	//should perhaps interlace vertex and normal ?
	glBindBuffer(GL_ARRAY_BUFFER, m_VBO);
	glVertexPointer(3*sizeof(float), GL_FLOAT, 0, (const float*)0);
	glNormalPointer(GL_FLOAT, 0, (const float*)0 + 3*m_numberOfVertices*sizeof(float));
	
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_IBO);
    glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_INT, 0);
    
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}